<template>

  <el-container style="overflow: hidden; height: 100%; width: 100%; ">

    <el-header height="auto" style=" border-bottom: 1px solid #060f1a12; ">
      <api-header></api-header>
    </el-header>

    <el-container class="appi-body-contaniner" style="overflow:auto;">

      <!--      <div style="width: 1200px; margin-left: 50%; left: -600px; position: relative; box-sizing: border-box;-->
      <!--           height: 60px; line-height: 60px;  padding: 0px 20px 0px 20px; ">-->
      <!--        <span style="font-size: 14px;">当前位置:  接口调试工具</span>-->
      <!--     -->
      <!--        <el-button @click="$jump('/app_info')" style="margin-left: 10px;">返 回</el-button>-->
      <!--      </div>-->

      <div class="api-body-contaniner">

        <el-form ref="formEl" :rules="rules" :model="formValue"
                 label-width="140px"
                 style=" box-sizing: border-box; padding: 60px 20px 20px 20px; position: relative;">

          <field-title title="应用参数信息"></field-title>

          <el-row>
            <el-col style="width: 480px;">

              <el-form-item label="测试应用">
                <el-select v-model="formValue.appId" clearable placeholder="">
                  <el-option
                    v-for="item in appInfoArr"
                    :key="item.id"
                    :label="item.appName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-col>
          </el-row>

          <el-row>

            <el-col style="width: 480px;">
              <el-form-item label="Api Token">
                <el-input v-model="formValue.apiToken"></el-input>
              </el-form-item>
            </el-col>

            <el-col style="width:200px; font-size:14px; color: #666; padding-top: 6px; padding-left: 12px;">
              <i class="el-icon-info"></i>&nbsp;需在客户端提前创建
            </el-col>

          </el-row>

          <el-row>
            <el-col style="width: 480px;">

              <el-form-item label="测试接口">

                <el-select v-model="formValue.apiCode" clearable placeholder="" filterable>
                  <el-option-group
                    v-for="group,groupIndex in apiRoot"
                    :key="'group_' + groupIndex"
                    :label="group.name">
                    <el-option
                      v-for="item in group.children"
                      :key="item.apiUrl"
                      :label="item.apiName"
                      :value="item.apiUrl">
                    </el-option>
                  </el-option-group>
                </el-select>

              </el-form-item>

            </el-col>
          </el-row>

          <el-row>
            <el-col style="width: 800px;">
              <el-form-item label="测试数据">
                <code-editor v-model="formValue.submitData" height="400px"></code-editor>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col style="width: 800px;">
              <el-form-item label="响应报文">
                <code-editor v-model="formValue.responseData" height="100px"></code-editor>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col style="width: 800px;">
              <el-form-item label="">
                <el-button @click="submitRequest" type="primary">提交请求</el-button>
                <el-button @click="showRequestData" v-if="debugShow" style="margin-left: 20px;">查看请求报文信息</el-button>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </div>

    </el-container>


    <el-dialog title="接口调试报文信息" :visible.sync="dialogFormVisible">
      <el-form :model="debugForm" labelWidth="100px">
        <el-form-item label="http地址">
          {{debugForm.address}}
        </el-form-item>
        <el-form-item label="http头信息">
          <div v-for="item,index in debugForm.header" style="display: flex">
            <div style="width: 120px;">{{item.key}}</div>
            <div>{{item.value}}</div>
          </div>
        </el-form-item>
        <el-form-item label="请求报文">
          {{debugForm.request}}
        </el-form-item>
        <el-form-item label="响应报文">
          {{debugForm.response}}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </el-container>

</template>

<script>

  import axios from 'axios'

  import ApiHeader from '../layout/api-header.vue'

  import CodeEditor from '@/component/code-editor.vue'

  export default {

    components: {ApiHeader, CodeEditor},

    data() {
      return {


        formValue: {
          'appId': '',
          'apiCode': '',
          'submitData': '',
          'apiToken': ''
        },

        rules: {
          appName: [
            {required: true, message: '请输入应用名称', trigger: 'blur'}
          ],
          callbackUrl: [
            {required: true, message: '请输入回传地址', trigger: 'callbackUrl'}
          ]
        },


        appInfoArr: [],
        appInfoMap: {},

        apiRoot: [],

        apiUrlCahce: {},

        debugForm: {
          'address': '',
          'header': [],
          'request': '',
          'response': ''
        },
        dialogFormVisible: false,

        debugShow: false

      };
    },

    watch: {
      'formValue.apiCode'(val, old) {
        // console.log(val)
        // console.log(this.apiUrlCahce[val])
        if (this.apiUrlCahce[val]) {
          this.formValue.submitData = this.apiUrlCahce[val].inputMock
        }
      }
    },

    created() {


      //

      let _this = this

      // 初始化接口
      _this.$getAllDocs(function (docs) {

        // xxx
        let apiUrlCahce = {}

        let erpGroups = docs.ERP
        let wmsGroups = docs.WMS

        erpGroups.forEach(group => {
          group.name = '[ERP] ' + group.name
          group.children.forEach(c => {
            _this.apiUrlCahce[c.apiUrl] = c
          })
        })
        wmsGroups.forEach(group => {
          group.name = '[WMS] ' + group.name
          group.children.forEach(c => {
            _this.apiUrlCahce[c.apiUrl] = c
          })
        })

        _this.apiRoot = erpGroups.concat(wmsGroups)

        // console.log(_this.apiRoot)

        // xxx

      })

      // 初始化应用
      _this.$ajax({
        url: '/open-api/open/OpenApiConfigRpc/queryAllApp.json',
        success: function (res) {
          if (res && res.data && res.data.rows) {

            let appInfoMap = {}
            res.data.rows.forEach(e => {
              appInfoMap[e.id] = e
            })

            _this.appInfoArr = res.data.rows
            _this.appInfoMap = appInfoMap

            if (_this.appInfoArr.length > 0) {
              _this.formValue.appId = _this.appInfoArr[0].id
            }
          }
        }
      })

    },

    mounted() {
      var _this = this;
    },

    destroyed() {
    },

    methods: {

      showRequestData() {
        this.dialogFormVisible = true
      },

      submitRequest() {

        let _this = this
        if (!_this.formValue.appId) {
          _this.$message.error('请选择应用');
          return
        }
        if (!_this.formValue.apiCode) {
          _this.$message.error('请选择接口');
          return
        }

        let appInfo = _this.appInfoMap[_this.formValue.appId]
        let apiObject = _this.apiUrlCahce[_this.formValue.apiCode]

        if (!appInfo || !apiObject) {
          _this.$message.error('数据异常');
          return
        }

        // 测试提交
        let appId = appInfo.appId
        let appSecret = appInfo.appSecret
        let timestamp = new Date().getTime()
        let postJson = _this.formValue.submitData
        let apiUrl = apiObject.apiUrl

        let headers = {}

        console.log(apiObject)

        // 请求开放平台
        if (apiObject.apiTo == 'KYB') {
          // 计算签名
          let appSign = _this.$md5(appSecret + timestamp + postJson)

          headers = {
            'Content-Type': 'application/json',
            "x-app-id": appId,
            "x-app-sign": appSign,
            "x-request-time": timestamp,
            "x-request-token": _this.formValue.apiToken
          }
        }
        // 通知客户
        else if (apiObject.apiFrom == 'KYB'){
          // /open-sdk/mms/query_sku_list
          let innerAppName = apiObject.apiUrl.substring(10)
          innerAppName = innerAppName.substring( 0, innerAppName.indexOf("/"))
          headers = {
            'Content-Type': 'application/json',
            "x-app-id": appId,
            "x-app-name": innerAppName + '-api',
            "x-api-code": apiObject.apiCode,
          }
          //
        }

        var config = {
          method: 'post',
          url:  apiObject.apiType == 'ResponseApi'? '/open-api-proxy' : apiUrl,
          headers: headers,
          data: postJson
        };

        _this.debugShow = false

        axios(config)
          .then(function (response) {

            _this.formValue.responseData = JSON.stringify(response.data)
            let debugHeaders = []
            for (let kk in headers) {
              debugHeaders.push({
                'key': kk, 'value': headers[kk]
              })
            }
            //
            _this.debugForm = {
              'address': window.location.origin + '' + apiUrl,
              'header': debugHeaders,
              'request': postJson,
              'response': _this.formValue.responseData
            }
            _this.debugShow = true

          })
          .catch(function (error) {
            _this.$message.error(error);
          });

      }

    }
  }

</script>
<style>

</style>
